package com.xinyu.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.xinyu.domain.User;
import com.xinyu.domain.UserSite;
import com.xinyu.service.IUserService;
import com.xinyu.service.IUserSiteService;
import com.xinyu.utils.EncryptionUtils;
import com.xinyu.utils.JWTUtils;
import com.xinyu.vo.BaseResult;
import com.xinyu.vo.LoginResult;
import com.xinyu.vo.UserRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author: XinYu
 * @since 2025-02-17
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private IUserSiteService userSiteService;

    @PostMapping("/login")
    public ResponseEntity<LoginResult> login(@RequestBody User user){
        LoginResult lr = null;

        //1 调用Service
        User dbUser = userService.findByPhone(user.getPhone());
        // 2 判断dbUser是否找到
        if(dbUser==null){
            lr = new LoginResult(0,"用户名不存在");
        }else {
            // 3 判断密码
            if(dbUser.getPwd().equals(EncryptionUtils.encryption(user.getPwd()))){
                // 4 登录成功
                String token = JWTUtils.generateToken(dbUser.getId(),dbUser.getUsername(),dbUser.getIsAdmin(),dbUser.getRole());
                lr = new LoginResult(token,dbUser.getId(),dbUser.getRealname(),dbUser.getIsAdmin(),dbUser.getRole());
            }else {
                // 密码错误
                lr = new LoginResult(0,"密码错误");
            }
        }
        return ResponseEntity.ok(lr);
    }

    /**
     * 注册的时候只需要提供：username.realname,phone,pwd
     * @param user
     * @return
     */
    @PostMapping("/regist")
    @Transactional
    public ResponseEntity<BaseResult> regist(@RequestBody User user){
        user.setPwd(EncryptionUtils.encryption(user.getPwd()));
        userService.save(user);
        for (Integer siteId:user.getSiteIds()){
            userSiteService.save(new UserSite(user.getId(),siteId));
        }
        return ResponseEntity.ok(BaseResult.ok());
    }

    /**
     * 更新的时候，支持更新部分字段和所有字段
     * @param user
     * @return
     */
    @RequestMapping(value = "/update", method = {RequestMethod.POST, RequestMethod.PUT})
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<BaseResult> modify(@RequestBody User user) {
        // 1. 更新用户基本信息（密码加密建议在Service层处理）
        userService.updateById(user);

        // 2. 清理旧关联
        userSiteService.remove(new LambdaQueryWrapper<UserSite>()
                .eq(UserSite::getUserId, user.getId()));

        // 3. 插入新关联（安全写法）
        if (CollectionUtils.isNotEmpty(user.getSiteIds())) {
            List<UserSite> relations = user.getSiteIds().stream()
                    .filter(Objects::nonNull)
                    .map(siteId -> new UserSite(user.getId(), siteId))
                    .collect(Collectors.toList());
            userSiteService.saveBatch(relations);
        }

        return ResponseEntity.ok(BaseResult.ok());
    }

    @PutMapping("pwd/update")
    public ResponseEntity<BaseResult> pwdModify(@RequestBody User user){
        User dbUser = userService.getById(user.getId());
        dbUser.setPwd(EncryptionUtils.encryption(user.getPwd()));
        userService.updateById(dbUser);
        return ResponseEntity.ok(BaseResult.ok());
    }

    @GetMapping("queryAll")
    public ResponseEntity<BaseResult> queryAll(){
        List<User> list = userService.list();
        return ResponseEntity.ok(BaseResult.ok(list));
    }

    @GetMapping("{id}")
    public ResponseEntity<BaseResult> queryById(@PathVariable Integer id){
        User user = userService.getById(id);
        return ResponseEntity.ok(BaseResult.ok(user));
    }

    @PostMapping("queryByCondition")
    public ResponseEntity<BaseResult> queryByCondition(@RequestBody UserRequest userRequest){
        BaseResult br = userService.queryByCondition(userRequest);
        return ResponseEntity.ok(BaseResult.ok(br));
    }

    @PostMapping("queryByPhone")
    public ResponseEntity<BaseResult> queryByPhone(@RequestBody User user){
        User dbUser = userService.lambdaQuery()
                .eq(User::getPhone, user.getPhone())
                .one();                     // 执行查询
        return ResponseEntity.ok(BaseResult.ok(dbUser));
    }

}

